When you’re training models, preprocessing and training can take forever. With a large dataset, two or three days can disappear before you know it. Discover a bug after two days and you get to start all over again. Here’s how to use profilers to find what’s slowing your program down.

The simple, easy-to-use Line Profiler

Line Profiler is somewhat invasive: you need to change your code manually.

First, the simplest step: install it.

1
pip install line_profiler

After installation, add @profile to your program as shown below. Some editors may warn that they can’t find the symbol.

1
2
3
4
5
6
7
8
9
10
11
12
from line_profiler import profile


@profile
def calculation():
x = 1
for i in range(10000):
x += i
return x


print(calculation())

Then, instead of running it directly, run:

1
2
kernprof -l <filename>.py
python -m line_profiler <filename.py>.lprof

kernprof produces profile files, but they aren’t plain ASCII files you can simply open. Use line_profiler to print their contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ python -m line_profiler .\exp.py.lprof            
Timer unit: 1e-06 s

Total time: 0.0036551 s
File: ./exp.py
Function: calculation at line 4

Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 @profile
5 def calculation():
6 1 0.4 0.4 0.0 x = 1
7 10001 1724.8 0.2 47.2 for i in range(10000):
8 10000 1929.7 0.2 52.8 x += i
9 1 0.2 0.2 0.0 return x

Easy to read, isn’t it? The annoying part is having to add @profile by hand to every function you want to inspect.

cProfile - More detail

cProfile is even more detailed and can even profile at the C level.

It can be used invasively or non-invasively.

For non-invasive use:

1
python -m cProfile -o myLog.profile <myScript.py> arg1 arg2

Here -o specifies the name of the saved profile file; you can omit it if you do not want one. The result looks like this:

1
2
3
4
5
6
7
8
9
10
      5 function calls in 0.001 seconds

Ordered by: internal time

ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.001 0.001 exp.py:2(calculation)
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
1 0.000 0.000 0.001 0.001 {built-in method builtins.exec}
1 0.000 0.000 0.001 0.001 exp.py:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

If you want to see a flame graph, you need to export the profile file:

1
flameprof pipeline.prof > pipeline.svg

The following produces a call graph, which is also fairly intuitive:

1
gprof2dot -f pstats myLog.profile -o callingGraph.dot

py-spy: Super convenient

A flame graph takes two commands with cProfile. Want one command instead? py-spy can do it without modifying your code:

1
py-spy record -o profile.svg -- python myprogram.py

torch.profiler

PyTorch includes a profiler for finding bottlenecks in neural-network computation. In my case, though, the bottleneck wasn’t the GPU at all—it was a single CPU core. How embarrassing.

1
2
3
4
5
6
7
8
9
10
11
12
13
from torch.profiler import profile, record_function, ProfilerActivity

with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], with_stack=True, record_shapes=True) as prof:
with torch.no_grad():
start_time = time.time()
for i in range(100):
s = model(dummy_graph)
end_time = time.time()
print("CUDA FP32 time: ", (end_time - start_time) / 10)

print(prof.key_averages(group_by_stack_n=5).table(sort_by="cpu_time_total",row_limit=10))
print(prof.key_averages( group_by_stack_n=5).table(sort_by="cuda_time_total", row_limit=10))
prof.export_stacks("./profiler_stacks.txt", "self_cuda_time_total")